/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package dao

import (
	"prim-server/model"

	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
)

type RoleDao struct {
	BaseDao
}

type IRoleDao interface {
	GetRoleName(roleId int) (*model.Role, error)
	InsertRole(role *model.Role) error
	GetRoleByName(roleName string) (*model.Role, error)
}

func GetRoleDao() IRoleDao {
	dao := &RoleDao{}
	dao.Init()
	return dao
}

func (ud *RoleDao) GetRoleName(roleId int) (*model.Role, error) {
	role := new(model.Role)
	role.Id = roleId
	err := ud.O.Read(role, "id")
	if err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, errors.Errorf("GetRoleName error: %v,roleId: %d", err, roleId)
	}
	return role, nil
}
func (ud *RoleDao) InsertRole(role *model.Role) error {
	if role == nil {
		return nil
	}
	_, err := ud.O.Insert(role)
	if err != nil {
		return errors.Errorf("InsertRole error:%v, roleId: %d, roleName: %s", err, role.Id, role.Name)
	}
	return nil
}

func (ud *RoleDao) GetRoleByName(roleName string) (*model.Role, error) {
	if len(roleName) == 0 {
		return nil, nil
	}
	role := new(model.Role)
	role.Name = roleName
	err := ud.O.Read(role, "name")
	if err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, errors.Errorf("GetRoleByName error: %v, roleName: %s", err, role.Name)
	}
	return role, nil
}
